#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
测试示例
演示了如何测试 FastAPI 应用
"""

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Union

app = FastAPI()

class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None

class User(BaseModel):
    username: str
    email: Union[str, None] = None
    full_name: Union[str, None] = None

# 模拟数据库
fake_items_db = [
    {"name": "Foo", "price": 50.2},
    {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
    {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
]

fake_users_db = {
    "alice": {"username": "alice", "email": "alice@example.com", "full_name": "Alice Wonderson"},
    "bob": {"username": "bob", "email": "bob@example.com", "full_name": "Bob Builder"},
}

def fake_user_access_token_dependency(token: str = "fake_token"):
    if token != "fake_token":
        return None
    return fake_users_db["alice"]

@app.get("/")
async def read_main():
    return {"msg": "Hello World"}

@app.get("/items/")
async def read_items():
    return fake_items_db

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id >= len(fake_items_db):
        return {"error": "Item not found"}
    return fake_items_db[item_id]

@app.post("/items/")
async def create_item(item: Item):
    fake_items_db.append(item.dict())
    return item

@app.get("/users/me")
async def read_user_me(current_user: User = Depends(fake_user_access_token_dependency)):
    return current_user

@app.get("/users/{username}")
async def read_user(username: str):
    if username not in fake_users_db:
        return {"error": "User not found"}
    return fake_users_db[username]

# 测试代码
def test_read_main():
    from fastapi.testclient import TestClient
    client = TestClient(app)
    
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}

def test_read_items():
    from fastapi.testclient import TestClient
    client = TestClient(app)
    
    response = client.get("/items/")
    assert response.status_code == 200
    assert len(response.json()) == 3

def test_create_item():
    from fastapi.testclient import TestClient
    client = TestClient(app)
    
    new_item = {"name": "Test Item", "price": 10.5}
    response = client.post("/items/", json=new_item)
    assert response.status_code == 200
    assert response.json()["name"] == "Test Item"

if __name__ == "__main__":
    # 运行测试
    print("Running tests...")
    test_read_main()
    test_read_items()
    test_create_item()
    print("All tests passed!")
    
    # 启动服务器
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8009, log_level="info")